//index.js
//获取应用实例
const app = getApp()
const calendar = require('../../utils/calend.js')

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    explain: '',
    enkey: '',
    entext: '',
    d: '',
    showadd: false,
    showAdimg: true,
    week: '',
    cnCalendar: {},
    animationData: {},
  },
  //说明
  explaintext: function (e) {
    this.setData({
      explain: e.detail.value
    })
  },
  //key
  keytext: function (e) {
    this.setData({
      enkey: e.detail.value
    })
  },
  //内容
  bindArea: function (e) {
    this.setData({
      entext: e.detail.value
    })
  },
  //点击头像
  bindViewTap: function () {
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })
    // console.log(this.data.userInfo)
  },

  //点击添加按钮
  btnadd: function () {
    //显示添加动画
    var animation = wx.createAnimation({
      duration: 500, //动画持续时间500ms
      timingFunction: 'ease', //动画以低速开始，然后加快，在结束前变慢
      delay: 0 //动画延迟0
    })
    this.animation = animation
    //Y平移
    animation.translateY(300).step()
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 10)

    this.setData({
      showadd: true,
      showAdimg: false,
      animationData: animation.export(),
    })
  },
  //提交按钮
  submitTo: function () {
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '先授权！',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    if (this.data.explain.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: '说明不能为空！',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    if (this.data.enkey.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: 'key不能为空！',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    if (this.data.entext.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: '内容不能为空！',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    this.setData({
      explain: this.data.explain,
      enkey: this.data.enkey,
      entext: this.data.entext,
    })
    // 点击保存数据

    wx.showLoading({
      title: '保存中...',
    })
    let that = this


    //查说明数据
    //console.log(that.data.entext)
    const db = wx.cloud.database()
    const collection = db.collection('person_memo')
    collection.where({
      description: that.data.explain,
      _openid: app.globalData.openid 
    }).get({
      success: function (res) {
        // console.log(res)
        if (res.data.length === 0) {

          //key b64
          wx.cloud.callFunction({
            // 云函数名称
            name: 'base64',
            // 传给云函数的参数
            data: {
              flag: 'en',
              str: that.data.enkey,
            },
            success: function (res) {
              //console.log(res.result)
              that.data.enkey = res.result

              //
              //text b64
              wx.cloud.callFunction({
                name: 'base64',
                data: {
                  flag: 'en',
                  str: that.data.entext,
                },
                success: function (res) {
                  //console.log(res.result)
                  that.data.entext = res.result

                  //
                  // encrypt
                  wx.cloud.callFunction({
                    name: 'encryption',
                    data: {
                      flag: 'encrypto',
                      str: that.data.entext,
                      k: that.data.enkey,

                    },
                    success: function (res) {

                      //console.log(res.result)
                      that.data.entext = res.result

                      //
                      //存数据
                      //console.log(that.data.entext)
                      const db = wx.cloud.database()
                      const collection = db.collection('person_memo')
                      collection.add({
                        data: {
                          description: that.data.explain,
                          encodetext: that.data.entext,
                          due: that.data.d,
                        },
                        success: function (res) {
                          //console.log(res)
                          wx.hideLoading()
                          wx.showToast({
                            title: '保存成功！',
                            icon: 'success',
                          })

                          that.setData({
                            explain: '',
                            enkey: '',
                            entext: '',
                          })
                        },
                        fail: function () {
                          wx.hideLoading()
                          wx.showToast({
                            title: '保存失败！',
                            icon: 'none',
                          })
                        },
                      })
                      //存数据 end

                    },
                    fail: function () {
                      wx.hideLoading()
                      wx.showToast({
                        title: '请求失败！',
                        icon: 'none',
                      })
                      console.error
                    }
                  })

                  //encrypt end
                },
                fail: function () {
                  wx.hideLoading()
                  wx.showToast({
                    title: '请求失败！',
                    icon: 'none',
                  })
                  console.error
                }
              })
              //text b64 end

            },
            fail: function () {
              wx.hideLoading()
              wx.showToast({
                title: '请求失败！',
                icon: 'none',
              })
              console.error
            }

          })
          //key b64 end


        } else {
          wx.hideLoading()
          wx.showToast({
            title: '已有相同的说明！保存失败。',
            icon: 'none',
          })
        }
      },
      fail: function () {
        wx.hideLoading()
        wx.showToast({
          title: '请求失败！',
          icon: 'none',
        })
        console.error

      }
    })
    //查说明数据 end



    //日期
    let dt = new Date()
    this.data.d = dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + " " + dt.getHours() + ":" +
      dt.getMinutes() + ":" + dt.getSeconds()

  },

  onLoad: function () {

    if (app.globalData.userInfo) {
      this.setData({

        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }


    //opeinid
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        //console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
      },
      fail: err => {
        wx.showToast({
          title: '请求失败！',
          icon: 'none',
        })
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })

  },
  // 星期数字转为大写
  wk: function (w) {
    var a = ['日', '一', '二', '三', '四', '五', '六']
    return a[w]
  },
  // 定时器取最新日期 
  timerweek: function () {
    let dt = new Date()
    this.data.cnCalendar = calendar.solar2lunar(dt.getFullYear(), (dt.getMonth() + 1), dt.getDate())
    this.data.week = (dt.getMonth() + 1) + '月' + dt.getDate() + '日 星期' + this.wk(dt.getDay())
    setTimeout(this.timerweek, 1000)
    this.setData({
      week: this.data.week,
      cnCalendar: this.data.cnCalendar,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.timerweek()

    this.setData({
      showadd: false,
      showAdimg: true,
      explain: '',
      enkey: '',
      entext: '',
      week: this.data.week,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {


    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: 'oix87密文档',
      path: '/pages/index/index'
    }

  }


})